package com.gitee.zhziyun.meowchat.meowserver;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.zhziyun.meowchat.common.model.Message;
import com.gitee.zhziyun.meowchat.meowserver.utils.DBUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MeowMaster {
    public static void main(String[] args) throws IOException {
        int port = 10000;
        ServerSocket meowServer = new ServerSocket(port);
        System.out.println("等待连接，端口：10000");

        new DBUtil();
        BlockingQueue<String> msgQueue = new LinkedBlockingQueue<>();    //定义消息队列
        List<MeowWorker> meowWorkers = new LinkedList<>();
        new Thread(new A(msgQueue, meowWorkers)).start();

        while (true) {
            MeowWorker meowWorker = new MeowWorker(meowServer.accept(), msgQueue);
            meowWorkers.add(meowWorker);
            new Thread(meowWorker).start();
        }
    }

    private static class A implements Runnable {
        private BlockingQueue<String> msgQueue;
        private List<MeowWorker> meowWorkers;
        private final ObjectMapper objectMapper = new ObjectMapper();

        public A (BlockingQueue<String> msgQueue, List<MeowWorker> meowWorkers) {
            this.msgQueue = msgQueue;
            this.meowWorkers = meowWorkers;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    String msg = msgQueue.take();
                    System.out.println(msg);
                    Message message = objectMapper.readValue(msg, Message.class);
                    for (MeowWorker meowWorker : meowWorkers) {
                        if (message.getTo() == meowWorker.getUserId()) {
                            meowWorker.receiveMsg(msg);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
